package com.forward.mobile.optitrans.db;

import java.sql.*;

public class Connector {

	private String host;
	private String base;
	private String user="root";
	private String password="admin";
	private Connection c;

	/**
	 * 
	 * @param host : The host name of addresse
	 * @param database : Database name :
	 * @param user user login
	 * @param password user password
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws ClassNotFoundException : if mysql driver is not imported
	 */
	public Connector(String host, String database, String user, String password) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		this.host = host;
		this.base = database;
		this.user = user;
		this.password = password;
	}
        
        public Connector() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		this.host = "localhost";
		this.base = "forward";
		this.user = "android";
		this.password = "sbougounika";
	}
	public void setDatabase(String databasename)
	{
		this.base=databasename;
	}
	
	public void startTransaction() throws SQLException {
		this.c.setAutoCommit(false);
	}
	
	public void commit() throws SQLException {
		this.c.commit();
		this.c.setAutoCommit(false);
	}
	
	public void rollback() throws SQLException {
		this.c.rollback();
		this.c.setAutoCommit(false);
	}
	
	public ResultSet execute(String request) throws SQLException {
		Statement s = this.c.createStatement();
		ResultSet rs = s.executeQuery(request); 
		return rs;
	}
	
	public int executeUpdate(String request) throws SQLException {
		Statement s = this.c.createStatement();
		return s.executeUpdate(request);		
	}
        public PreparedStatement getPrepareStatement(String statement) throws SQLException{
            return this.c.prepareCall(statement);
        }

	public void open() throws SQLException {
		this.c = DriverManager.getConnection("jdbc:mysql://"+this.host+"/"+this.base, user, password);
	}
	
	public void close() throws SQLException {
		this.c.close();
	}
	
	
	public static String txtAttr(String attr) {
		return attr.replaceAll("'", "''");
	}
}
